/**
 * 请求
 */
import { IType, Schema } from './schema.js';
import { openApiTypeToTypescriptType } from './utils.js';

export interface MethodMarkdown {
    /** 路径 */
    path: string;
    /** 名称 */
    name: string;
    /** 描述 */
    description: string;
    /** 请求类型 */
    response?: IType;
    /** 响应类型 */
    request?: IType;
    /** 参数 */
    params: MethodParamMarkdown[];
}

export interface MethodParamMarkdown {
    /** 名称 */
    name: string;
    /** 位置 */
    position: string;
    /** 描述 */
    description: string;
    /** 是否必填 */
    required: boolean;
    /** 类型 */
    type: IType;
}

export class Request {
    /** 路径 */
    readonly path: string;
    /** 请求方式 */
    readonly method: string;
    /** 标签即service */
    readonly tags?: string[];
    /** 描述 */
    readonly summary: string;
    /** 参数 */
    readonly parameters: RequestParam[];
    /** 名称 */
    readonly operationId: string;
    readonly response?: IType;
    readonly request?: IType;

    constructor(path: string, method: string, value: any, schemas: Map<string, Schema>) {
        this.path = path;
        this.method = method;
        this.tags = value.tags;
        this.summary = value.summary;
        this.operationId = value.operationId;
        this.parameters = value.parameters?.map((param: any) => new RequestParam(param, schemas)) || [];
        const request = value.requestBody?.content?.['application/json']?.schema;
        if (request) {
            this.request = openApiTypeToTypescriptType(schemas, request.type, request.format, request.$ref, request.items);
        }
        const response = value.responses?.['200'].content?.['*/*']?.schema;
        if (response) {
            this.response = openApiTypeToTypescriptType(schemas, response.type, response.format, response.$ref, response.items);
        }
    }

    getMarkdown(): MethodMarkdown {
        return {
            params: this.parameters.map(v => v.getMarkdown()),
            path: this.path,
            description: this.summary,
            name: this.operationId,
            request: this.request,
            response: this.response
        };
    }
}

export class RequestParam {
    /** 名称 */
    name: string;
    /** 位置 */
    position: string;
    /** 描述 */
    description: string;
    /** 是否必填 */
    required: boolean;
    /** 类型 */
    type: IType;

    constructor(value: any, schemas: Map<string, Schema>) {
        this.name = value.name;
        this.description = value.description;
        this.position = value['in'];
        this.required = value.required;
        this.type = openApiTypeToTypescriptType(schemas, value.schema.type, value.schema.format, value.schema.$ref, value.schema.items);
    }

    getMarkdown(): MethodParamMarkdown {
        return this;
    }
}
